package com.ly.blog_user.security;


import com.ly.blog_common.entity.SysUserEntity;
import com.ly.blog_common.security.GrantedAuthorityImpl;
import com.ly.blog_common.security.JwtUserDetails;
import com.ly.blog_user.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 用户登录认证信息查询
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username){
		SysUserEntity user = sysUserService.queryByUserName(username);
		if(user == null) {
            user = sysUserService.queryByEmail(username);
        }

        // 账号不存在、密码错误  会被拦截异常，后续输出权限不够，异常不正确
		if(user == null) {
            return new JwtUserDetails(user, null);
		}

        // 用户权限列表，根据用户拥有的权限标识与如  那个业务-那个模块-那个功能
        // @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        List<GrantedAuthorityImpl> grantedAuthorities = new ArrayList<>();
        sysUserService.getUserPermissions(user.getUserId())
                .stream()
                .forEach(perms -> {
                    if(StringUtils.isNotBlank(perms)){
                        Arrays.stream(perms.split(","))
                                .forEach(perm -> grantedAuthorities.add(new GrantedAuthorityImpl(perm)));
                    }
                });
        return new JwtUserDetails(user,grantedAuthorities);
    }
}